package id.co.rho.scoring.cid.client.widgets;

import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.util.Util;
import com.extjs.gxt.ui.client.widget.button.Button;
import gxt.visual.ui.client.implementations.VTextField;

public class DirtyAwareTextFieldNButton<D> extends TextFieldWithButton<D> implements DirtyAwareField<D> {

	Listener changeListener = new Listener<FieldEvent>() {
	      public void handleEvent(FieldEvent be) {
	        onFieldChange(be);
	      }
	    };

	/**
	 * Dirtyness previous state.
	 */
	boolean dirtyPrevState = false;

	public DirtyAwareTextFieldNButton(Button button) {
        super(button);
		addListener(Events.Change, changeListener);
	}
	
	@Override
	public void resetDirtyness() {
		dirtyPrevState = false;
		UIHelper.removeDirtyMarker(this);
		onFieldChange(null);
	}

	private void onFieldChange(FieldEvent be) {
		boolean dirty = !Util.equalWithNull(getOriginalValue(),getValue());
		if(dirty != dirtyPrevState) {
			dirtyPrevState = dirty;
			if(dirty) {
				UIHelper.applyDirtyMarker(this);
			}else {
				UIHelper.removeDirtyMarker(this);
			}
		}
	}
	
}
